lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
+90
-28
@@ -1,37 +1,99 @@
|
||||
# Матрица доверия — заполнить в решении lab7
|
||||
# Матрица доверия — реализованный стенд lab7
|
||||
|
||||
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать.
|
||||
## Identities, CA и leases
|
||||
|
||||
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
|
||||
| --- | --- | --- | --- |
|
||||
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO |
|
||||
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO |
|
||||
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO |
|
||||
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO |
|
||||
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO |
|
||||
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
|
||||
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO |
|
||||
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO |
|
||||
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO |
|
||||
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO |
|
||||
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
|
||||
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
|
||||
Все TLS endpoints проверяются по CA и DNS SAN; TLS ≥1.2. Offline root находится
|
||||
у оператора вне checkout, OpenBao выдаёт EC P-256 leaf через внутренний intermediate.
|
||||
URI service identity — `spiffe://mtusi/<role>`; DNS SANs задаёт
|
||||
`scripts/lab7_environment.py:ROLES`. Доверенный CA сам по себе не является ACL.
|
||||
|
||||
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
|
||||
Default leaf TTL — 1h, максимум PKI role — 1h; host-side `make renewer`
|
||||
выпускает новые leaf каждые 30 минут и синхронизирует CRL; исследовательский renewal/expiry
|
||||
использует 20s. Cert-auth tokens: 60s, max/explicit max300s. KV freshness у Go
|
||||
приложения — 60s, независимо от срока leaf и token; admission закрывается за1s
|
||||
до ближайшего deadline (наблюдаемое закрытие при sealed Bao: 60.5–61.7s с учётом
|
||||
1s cadence watchdog). Backend KV passwords/SigV4 keys статические и живут до
|
||||
явной ротации — это не динамические60s credentials. Session TTL3600s;
|
||||
server хранит только SHA-256 token hash.
|
||||
|
||||
## Обязательные отрицательные проверки
|
||||
| Связь | Endpoint / протокол | Проверка identity и права | Lease / reload | Положительная и отрицательная проверка |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Клиент → ingress/LB | `https://localhost:8443`, TLS, Bearer | DNS SANlocalhost; без clientcert. LB заменяет forwarding headers и удаляет X-User-Id | LB leaf; пользовательская session3600s/logout/expiry | `make test test-security`; `public_ca_hostname`, `http_acl_logout_expiry_bounds`, `shared_rate_limit` |
|
||||
| LB → все API-реплики | `api-replica:8080`, native mTLS | LB проверяет SANapi-replica/CA/CRL; Go server требует точный URI`spiffe://mtusi/lb` | Atomic leaf/CRL reload Go; trust changes restart; tickets/cache off | `mtls_and_telemetry_acl`: lb200; absent/wrongCA/wrongURI TLS拒绝; `make test-pki` oldLB revoke/retire |
|
||||
| API/worker/relay → PostgreSQL | `postgres:5432`, native TLS+SCRAM, verify-full | Раздельные messenger_api/worker/relay roles; no superuser/DDL. Worker/relay не читают users/sessions/messages | Статический password в ownKV; connection lifetime30s; credentials change → bounded restart | `database_privileges`: SQLSTATE42501; `make integration-test` actual nativeTLS DB suites |
|
||||
| API/worker → S3 | `https://seaweedfs:8333`, native TLS+SigV4 | API stagingRead/Write, finalRead; worker managed-prefixRead/Write+bucketList; foreign GET/PUT/DELETE/COPY/bucket 403, worker bucket-level LIST returns managed metadata (documented limitation) | Static keys until explicitrotation; role-specific ownKV. No claim of required clientcert on S3HTTP | `s3_prefix_acl`: GET/PUT/DELETE/COPY+fullreadback; `make test-presign test-queue`; workerkeyrotation inPKIstudy |
|
||||
| Relay/API outbox/worker → broker | `broker:5671`, native mTLS/EXTERNAL-only | API commits DBoutbox, relay publishes onlyattachments.jobs; worker consumes onlyattachment.process.v1. First DNS SAN principal, anchored broker ACL | Leaf+broker user permissions; nativeprincipal revoke distinct from serial CRL | `broker_external_acl`: positive relaypublish/workerconsume; opposite/topology/wrongDNS403, no-cert/wrongCA TLS rejection |
|
||||
| API/worker/relay → Collector | `otel-collector:4318`, mTLS gateway → loopback14318 | Exact CNapi/worker/relay and POST/v1/{traces,metrics,logs}; unknownCN/verb/path denied | Gateway loads CA/CRL atstartup; revoke/rollover restarts gateways; app pools are not claimed drained | `mtls_and_telemetry_acl`: api200, lb403, missing/wrongCA rejection; full `make test-observability` |
|
||||
| Collector → telemetry backends | Loki`https://loki:3100`; TempoGRPCS`tempo:4437` | CollectorCN onlylogpush/OTLP; no dataquery. Native hops127.0.0.1:13100/14317 | Distinct collectorleaf; fixedsingletenantfake | `mtls_and_telemetry_acl` collectorquery403; actual traces/logs in `make test-observability` |
|
||||
| Grafana → data sources | Prometheus9090/Loki3100/Tempo3200, HTTPS/mTLS | GrafanaCN query allowlist; push/delete/admin/reload forbidden; CA+hostname verified | Ownleaf in secureJsonData rendered outsideGit; rotation rerenders/restarts | `mtls_and_telemetry_acl` forbiddenwrite403; Grafana/dataSources/TraceQL correlation intelemetrygate |
|
||||
| API/worker/relay → OpenBao | `https://openbao:8200`, verifiedTLS+cert-auth | Authrole checks CN+URI; ownsecret/data/<role> and ownpki/issue/<role> only; no root/defaultpolicy | Token60s/max300s; cert reauth; KVfresh60s; independentleafdeadline | `bao_api_policy`: ownKV200, foreignKV/issuer/policyadmin403; `make test-pki` renewal/expiry/recovery |
|
||||
| Оператор → OpenBao/Grafana/S3 admin | LoopbackHTTPS8200/3000/8333 | Separate operatorcertificate+scopedBaopolicy; Grafana localpassword; SigV4S3operator. No anonymousadmin | Root token revoked afterbootstrap; unseal2-of-3 hoststate; operatorleafrotation | `securityctl.py up`, `audit-summary`, S3readinessfullbytes; noappoperatorcredentialmounts inisolation |
|
||||
| API → Redis | `redis:6379`, nativeTLS+ACLpassword | `cache` user: chat_list:* / lock:chat_list:* onlyGET/SET/DEL/PING/EVAL/scripts; default useroff | StaticownKVpassword; RedisAOF persists; no requiredclientcert claimed | `redis_tls_cache_acl`: PONG/allowedcache, foreignkeyNOPERM; nativeTLS integrationDB7 |
|
||||
| Replication/cluster channels | ExternalreplicationN/A: allstatefulstores single-node | BaoRaftcluster127.0.0.1:8201nativeTLS; S3master/filer/volume oneclosednamespace, internalgRPCmTLSCNs3; telemetrygossiploopback | NoHAclaim forDB/S3/broker/Bao/host | `runtime_container_network_isolation`; `seaweed_auxiliary_mtls`; actualpersistence/bothAPIreplicafailures |
|
||||
|
||||
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен».
|
||||
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех.
|
||||
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity.
|
||||
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity.
|
||||
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3.
|
||||
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить.
|
||||
## Служебные, scrape и health каналы
|
||||
|
||||
## Bootstrap и эксплуатация
|
||||
| Канал | Boundary / identity | Проверка |
|
||||
| --- | --- | --- |
|
||||
| Local API/worker/relay health8084/8081/8082 | Namespace loopback, no business API; no hostpublication | Из соседнего defaultnamespaceconnection_refused; Gohealthcloses admission onauthorizationexpiry |
|
||||
| HAProxy stats8404 | mTLS, CNoperator/prometheus; monitoronly/metrics | Separate healthbackend excluded fromAPI SLI; Prometheus scrape overTLS |
|
||||
| Collector metrics8888/8889, health13134 | mTLS/CNprometheus oroperator; localhops18888/18889/13133 | Privateportprobes, fulltelemetryscrapes |
|
||||
| Prometheus/Loki/Tempo selfmetrics | HTTPS/mTLS/CNprometheus GETmetrics/ready only | Wrongqueryrole403; native19090/13100/13200 andgRPC/gossip notnetwork-accessible |
|
||||
| RabbitMQ management15671, scrape15693 | mTLS HAProxy → loopback15672/15692; operatoradmin Basic onlymanagement, Prometheus onlyscrape | NoAMQP5672 orplaintextmanagement published; brokerACL/scapedata |
|
||||
| S3 auxiliary18333 | Native mTLS, onlyCNs3; HTTP2 ALPNh2 | api/worker/operator/no-cert denied, s3TLSchannelaccepted; not anadminmethodproof |
|
||||
| S3 master/filer/volume | HTTP9333/8888/8080 andgRPC19333/18888/18080 onnamespace loopback; gRPC additionallyCNs3 | Neighbor namespaceconnection_refused; Iceberg8181/Lance9101 disabled, not excluded |
|
||||
| Migrations/S3-init/volume-init | Explicitoperatorjobs; no rootCA/unseal mount | Migrate DBoperator only; S3init operator only; volume-init has no network/socket, CHOWN/DAC_OVERRIDE only |
|
||||
|
||||
В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу.
|
||||
Native plaintext hops exist **only within the shared Linux network namespace**
|
||||
of a backend+its TLS gateway, or S3co-located internal HTTP components. A helper
|
||||
compares actual `/proc/self/ns/net`, not just containerIDs. None of these listeners
|
||||
is a published bypass; only TLS owner joins routable networks. `default` is used
|
||||
by apps, `observability` by telemetry, `edge` by their TLS owners.
|
||||
|
||||
OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии.
|
||||
## Bootstrap, current-version и отзыв
|
||||
|
||||
Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap.
|
||||
1. `cp .env.example .env; make up`: offlinekeys/backendcredentials/complete role
|
||||
versions are generated locally; init/unseal/provision/migrations follow.
|
||||
2. RootCA/privateoperator/unseal state is in `~/.local/share/mtusi-lab7/<project>`
|
||||
with0700/0600. Only public CA/intermediate/CRLs and each role's own leaf/key
|
||||
enter role mounts. Operator recovery material never enters app/images/Git.
|
||||
3. Native consumers use `current` alias. Every Go snapshot reads one bounded
|
||||
regular `current-version` selector and immutable `versions/<name>`; cert/key/CA/CRL
|
||||
cannot be mixed across a swap. Selector is owner/group-readable before atomic
|
||||
publication. No last-known-invalid fallback, arbitrary path or symlink retry.
|
||||
4. `make pki-renew ROLE=api CERT_TTL=1h` and `renew-watch` use owncert-auth. Token
|
||||
renewal cannot renew theleaf. Missing/expired/revoked material fails closed.
|
||||
5. `securityctl.py revoke ROLE --serial SERIAL`: publishes issuer-signed CRLs,
|
||||
updates BaoauthCRLs, then restarts native CRL-consuming HAProxy gateways.
|
||||
Existing application TLS/DB/S3/broker pools are not claimed to be drained;
|
||||
only fresh/resumption attempts are measured.
|
||||
Go verifies currentCRLs onfreshconnections. Principalcompromise also requires
|
||||
backendcredential/token/authrole disable; RabbitMQ EXTERNAL user/connection
|
||||
revocation is separate and not falsely represented by CRLfileupdate.
|
||||
6. Offline rootCRLs are regenerated before their final24h and onoperator sync;
|
||||
nativegateways are reconciled on `up`. StaleCRL verification is never disabled.
|
||||
7. CArollover uses prepare(overlapCA/CRLs+authtrust) → issue(newintermediate/leaves)
|
||||
→ retire(oldCA/issuer/authCRLs). Retire re-publishes every running role identity
|
||||
with a new-only trust bundle (the leaf is unchanged), so an old certificate is
|
||||
rejected by trust, not by a missing CRL; a process whose mounted trust differs
|
||||
from its startup roots fails closed (`restart required`). Prepare/retire reload
|
||||
api/worker/relay one replica at a time; issue only reloads native owners and
|
||||
Go re-reads the new leaf on fresh handshakes. Readiness closes on root removal
|
||||
so LB retires a not-yet-restarted replica instead of routing into TLS failures.
|
||||
Study checks oldtrustedleaf during overlap, fresh/resumption attempts after
|
||||
retirement, newpipeline/Redis/Bao/telemetry paths and retained message/filebytes;
|
||||
each phase waits for the full
|
||||
public upload pipeline before asserting contract details.
|
||||
|
||||
## Обязательные отрицательные наборы
|
||||
|
||||
- CA/hostname errors are checked as verification errors, not TCPtimeouts.
|
||||
- API/broker/Collector: allowedidentitypositive, absentcert, foreignCA andsameCA
|
||||
forbiddenrole negatives. HTTP403 aftertrustedmTLS is distinguished from TLSdenial.
|
||||
- Foreignchat/attachment access, forgedX-User-Id, logout/DBexpiry, uploadbounds,
|
||||
shared429/Retry-After, nativeDB/S3/broker/Baopolicy allow/deny are runtime-tested.
|
||||
- Leaf/CArevocation checks freshconnections and explicit resumptionattempts;
|
||||
tickets/cacheoff means no claim of a positively resumedsession.
|
||||
- `evidence/lab7/security.json`, `verification.json`, `restart-scope.json`,
|
||||
`failover-scope.json`, `sequential-failover.json` andPKIstudy contain sanitized
|
||||
observations; [scantriage](../security/SCAN_TRIAGE.md) names residualrisk.
|
||||
|
||||
Reference in New Issue
Block a user