docs: translate security.md and the last Russian source comments

security.md is linked from the README documentation table and now from
SECURITY.md, so a reader following either link landed in a Russian document
while everything around it was English. Translated in full; the requirements,
the accepted risks, and the CSRF ADR are unchanged in substance.

The reviewing model is no longer named in the text — that the pre-release
review ran, and when, is what a reader needs; who ran it is process detail
kept in development.md.

extract-cert.sh keeps its spec 10.3 quotation, translated. In sasl.go the
quotation from the closed plan is dropped rather than translated: rendered in
English it restated the sentence it hung off.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-09 22:39:53 +03:00
parent 04993e0da3
commit 236cb07769
4 changed files with 173 additions and 147 deletions
+11
View File
@@ -15,6 +15,17 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); version
### Changed ### Changed
- [docs/security.md](docs/security.md) is now in English, matching the rest of
the published docs — it is linked from the README table and from
`SECURITY.md`, so a reader following either landed in Russian. Content is
unchanged: same requirements, same accepted risks, same ADR. The reviewing
model is no longer named in the text; the fact that a pre-release review ran,
and its date, stay.
- The two remaining Russian source comments are in English:
`deploy/traefik/extract-cert.sh` (quote from spec 10.3) and
`internal/app/sasl.go`, where the quotation from the closed plan is dropped
rather than translated — rendered in English it restated the sentence it was
attached to.
- The panel's **Account** entry is now called **Settings** — nav link, page - The panel's **Account** entry is now called **Settings** — nav link, page
heading, and browser title. The route stays `/account`, so existing links heading, and browser title. The route stays `/account`, so existing links
and bookmarks are unaffected. and bookmarks are unaffected.
+4 -4
View File
@@ -1,9 +1,9 @@
#!/bin/sh #!/bin/sh
# Extracts a PEM cert/key pair for one domain out of Traefik's acme.json # Extracts a PEM cert/key pair for one domain out of Traefik's acme.json
# (spec 10.3: "Traefik — сертификаты в acme.json, потребуется шаг извлечения # (spec 10.3: "Traefik keeps certificates in acme.json, so a PEM extraction
# PEM"). Run this on the host, after Traefik has issued or renewed the # step is required"). Run this on the host, after Traefik has issued or
# certificate, and again on a schedule (cron/systemd timer) since acme.json # renewed the certificate, and again on a schedule (cron/systemd timer) since
# is not itself watched by SelfPost/Postfix. # acme.json is not itself watched by SelfPost/Postfix.
# #
# Requires jq. Usage: ./extract-cert.sh <acme.json path> <domain> <output dir> # Requires jq. Usage: ./extract-cert.sh <acme.json path> <domain> <output dir>
set -eu set -eu
+157 -141
View File
@@ -1,177 +1,193 @@
# Безопасность # Security
**Что здесь.** (1) **Обязательные требования** — чеклист, который v1.0 обязан **What is here.** (1) **Mandatory requirements** — the checklist v1.0 has to
выполнять; полный аудит на v1.0 пройден. Предрелизная ревизия (план § D, meet; the full v1.0 audit passed. The pre-release review (plan § D, 2026-08-06)
модель Fable, 2026-08-06) прошла по всему дифу от аудита v1.0 (Фаза 11) до covered the whole diff from the v1.0 audit (Phase 11) to HEAD and the checklist
HEAD и по чек-листу целиком: эксплуатируемых находок нет; одна правка in full: no exploitable findings; one defence-in-depth change — `--` before the
defence-in-depth — `--` перед логином в argv `saslpasswd2` login in the `saslpasswd2` argv
([internal/app/sasl.go](../internal/app/sasl.go)). (2) **Принятые риски** ([internal/app/sasl.go](../internal/app/sasl.go)). (2) **Accepted risks**
сознательные отступления сверх обязательного, чтобы решение не потерялось. deliberate departures beyond the mandatory, recorded so the decision is not
lost.
Hardening сверх обязательного (security-заголовки, проверка origin, cookie Hardening beyond the mandatory (security headers, origin checking, `__Host-`
`__Host-` с обнаружением дублей — Фаза 14) закрыт; история — в cookie with duplicate detection — Phase 14) is done; the history is in
[CHANGELOG.md](../CHANGELOG.md) и `git log`. [CHANGELOG.md](../CHANGELOG.md) and `git log`.
Продуктовые границы: [product.md](product.md). Устройство as-built: Product boundaries: [product.md](product.md). As-built design:
[architecture.md](architecture.md). [architecture.md](architecture.md).
--- ---
## Обязательные требования ## Mandatory requirements
Панель публична из интернета — пункты ниже **не опциональны**. The panel is exposed to the internet — the items below are **not optional**.
### Первичная инициализация администратора ### First-run administrator setup
- Одноразовая secret-ссылка `/setup/<token>`, **не** env с готовым хэшем пароля. - A one-time secret link `/setup/<token>`, **not** an env variable holding a
- Токен ≥128 бит (`crypto/rand`); дублируется в `/data/setup-token`. ready-made password hash.
- Срок жизни токена — **10 минут**; после истечения или рестарта без завершённой - Token ≥128 bits (`crypto/rand`); mirrored to `/data/setup-token`.
настройки — перегенерация и новый вывод в лог. - Token lifetime — **10 minutes**; after expiry, or after a restart with setup
- Rate limiting на `/setup/<token>` по IP, отдельно от логина. unfinished, it is regenerated and logged again.
- Сравнение токена — **константное по времени** (`subtle.ConstantTimeCompare`). - Rate limiting on `/setup/<token>` per IP, separate from login.
- Неудачные попытки **не** инвалидируют токен досрочно (защита от DoS настройки). - Token comparison is **constant-time** (`subtle.ConstantTimeCompare`).
- После создания администратора — токен навсегда недействителен, `/setup/*` → 404. - Failed attempts do **not** invalidate the token early (protects setup from
- Пароль администратора — только bcrypt (или argon2) в SQLite; без plaintext/MD5. being DoS-ed).
- `PANEL_USERNAME` / `PANEL_PASSWORD_HASH` в env **не используются**. - Once the administrator exists the token is void forever, `/setup/*` → 404.
- The administrator password is bcrypt (or argon2) in SQLite only; no plaintext
and no MD5.
- `PANEL_USERNAME` / `PANEL_PASSWORD_HASH` in env are **not used**.
### SASL-пароли приложений ### Application SASL passwords
- Панель **генерирует** пароль при создании/перевыпуске, показывает **один раз**. - The panel **generates** the password on creation or reissue and shows it
- В `sasldb2` — в форме, требуемой SASL (не plaintext в панели); утерян — только **once**.
перевыпуск. - In `sasldb2` it is stored in the form SASL requires (not plaintext held by the
panel); a lost password can only be reissued.
### Ввод и конфигурация ### Input and configuration
- Серверная валидация email/доменов (whitelist символов); клиентская не считается - Server-side validation of addresses and domains (character whitelist);
защитой. client-side validation does not count as protection.
- Режим «список адресов» — каждый адрес принадлежит домену приложения до записи. - In address-list mode every address is checked to belong to the application's
- `postfix reload` и любой `exec`**без** shell-интерполяции пользовательского domain before it is written.
ввода; аргументы отдельными элементами. - `postfix reload` and any `exec` run **without** shell interpolation of user
- Запись в конфиг-файлы — с экранированием (нет инъекции директив Postfix). input; arguments are passed as separate elements.
- Writes to config files are escaped (no injection of Postfix directives).
### Аутентификация и сессии ### Authentication and sessions
- Rate limiting на логин (по IP, с блокировкой/задержкой). - Rate limiting on login (per IP, with lockout or delay).
- Сессии: криптографически случайный токен; cookie `HttpOnly`, `Secure`, `SameSite`. - Sessions: cryptographically random token; cookie `HttpOnly`, `Secure`,
- Сессии в SQLite (SHA-256 токена, не сам токен); скользящий idle `SameSite`.
(`PANEL_SESSION_IDLE_DAYS`). - Sessions live in SQLite (SHA-256 of the token, not the token itself); sliding
idle timeout (`PANEL_SESSION_IDLE_DAYS`).
### Вывод и процесс ### Output and process
- Рендер через `html/template` с автоэкранированием (очередь, лог, журнал, темы). - Rendering goes through `html/template` with auto-escaping (queue, log,
- Процесс панели **не root** (`user=panel` в supervisord); доступ к путям через journal, themes).
группу `selfpost` и минимальные права. - The panel process is **not root** (`user=panel` in supervisord); path access
is granted through the `selfpost` group with minimal permissions.
### Почтовый тракт (связанное с безопасностью) ### Mail path (security-relevant)
- **Не open relay** — только SASL; `reject_unauth_destination`; - **Not an open relay** — SASL only; `reject_unauth_destination`;
`smtpd_sender_login_maps` + `reject_sender_login_mismatch`. `smtpd_sender_login_maps` + `reject_sender_login_mismatch`.
- TLS обязателен до передачи кредов (465 wrapper / 587 `encrypt`). - TLS is mandatory before credentials are transmitted (465 wrapper / 587
- `TRUSTED_PROXY_CIDR` — только явно доверенные прокси для `X-Forwarded-For` `encrypt`).
при rate-limit логина; пусто = XFF игнорируется. - `TRUSTED_PROXY_CIDR` — only explicitly trusted proxies may supply
`X-Forwarded-For` for login rate limiting; empty means XFF is ignored.
### Резервная копия и экспорт домена ### Backup and domain export
- Оба файла — секреты: полный бэкап несёт DKIM-ключи, `sasldb2` и хеш пароля - Both files are secrets: a full backup carries DKIM keys, `sasldb2`, and the
админа; экспорт домена — DKIM-ключ и **рабочие** пароли приложений открытым administrator's password hash; a domain export carries the DKIM key and
текстом (иначе перенос без пересоздания кредов невозможен). **working** application passwords in the clear (otherwise a transfer without
- Оба скачивания можно зашифровать паролем (чекбокс в форме): scrypt recreating credentials would be impossible).
(N=2¹⁵, r=8, p=1) → AES-256-GCM, поток из 64 KiB чанков, каждый - Both downloads can be encrypted with a password (a checkbox on the form):
аутентифицирован заголовком, номером и флагом конца потока — обрезанный или scrypt (N=2¹⁵, r=8, p=1) → AES-256-GCM, streamed in 64 KiB chunks, each
подменённый файл не открывается вместо тихого восстановления «хвоста». authenticated with the header, the chunk number, and an end-of-stream flag —
Формат и обёртка: [internal/secretfile](../internal/secretfile/secretfile.go). a truncated or substituted file fails to open instead of silently restoring a
- Расширения: `.spbk` (**S**elf**P**ost **b**ac**k**up — полный бэкап), partial "tail". Format and wrapper:
`.spde` (**S**elf**P**ost **d**omain **e**xport — экспорт домена); [internal/secretfile](../internal/secretfile/secretfile.go).
незашифрованные остаются `.tar.gz` / `.json`. Импорт домена определяет - Extensions: `.spbk` (**S**elf**P**ost **b**ac**k**up — full backup), `.spde`
шифрование по magic файла, а не по расширению. (**S**elf**P**ost **d**omain **e**xport — domain export); unencrypted files
- Пароль нигде не сохраняется: восстановить файл без него нельзя. Пароль в CLI — stay `.tar.gz` / `.json`. Domain import detects encryption by the file's magic
только через `SELFPOST_BACKUP_PASSWORD` или `-password-file`, никогда bytes, not by extension.
аргументом (список процессов читается любым процессом контейнера). - The password is never stored: without it the file cannot be recovered. In the
- Минимальная длина пароля — как у пароля администратора (12): файл лежит CLI the password comes only from `SELFPOST_BACKUP_PASSWORD` or
offline и подбирается без ограничений по времени. `-password-file`, never as an argument (the process list is readable by any
process in the container).
- Minimum password length matches the administrator password (12): the file
sits offline and can be attacked without a time limit.
--- ---
## Принятые риски ## Accepted risks
Принятый риск — решение с условием возврата, а не отложенная задача из An accepted risk is a decision with a condition for revisiting it, not a
дорожной карты. deferred item from the roadmap.
- **`POST` без `Sec-Fetch-Site` и без `Origin` пропускается.** - **A `POST` with neither `Sec-Fetch-Site` nor `Origin` is allowed through.**
Клиент, не посылающий ни одного из двух — по-настоящему старый браузер или A client that sends neither — a genuinely old browser, or a webview with a
webview с замороженным движком, — остаётся уязвим к CSRF с любого сайта. frozen engine — stays vulnerable to CSRF from any site. Accepted
Принято сознательно: панель однопользовательская, админ выбирает браузер deliberately: the panel is single-user, the administrator picks the browser,
сам, а строгий режим не «защитил бы» такой клиент, а просто сломал бы в нём and a strict mode would not "protect" such a client, it would simply break the
панель. Ужесточение — одна строка в `originAllowed` panel in it. Tightening is one line in `originAllowed`
([internal/web/security.go](../internal/web/security.go)): вернуть `false` ([internal/web/security.go](../internal/web/security.go)): return `false`
вместо `true` в ветке «нет обоих заголовков». instead of `true` in the "neither header present" branch.
- **CSRF-токены, привязанные к сессии, не делаются.** Проверка origin - **Session-bound CSRF tokens are not implemented.** The origin check closes the
закрывает соседний поддомен, но зависит от поведения браузера; токен — нет. neighbouring-subdomain case but depends on browser behaviour; a token does
Цена — скрытое поле примерно в двух десятках форм. Триггером вернуться к not. The price is a hidden field in roughly two dozen forms. The trigger to
вопросу считать появление требования «устойчиво независимо от браузера». revisit is a requirement for protection that holds regardless of the browser.
От XSS внутри самой панели не спас бы и токен: код, исполняющийся в origin A token would not save the panel from XSS inside it either: code executing in
панели, отправит запрос сам — против этого работают автоэкранирование the panel's origin sends the request itself — against that, `html/template`
`html/template` и CSP, поэтому шаблоны не должны содержать auto-escaping and CSP do the work, which is why templates must contain no
inline-скриптов и inline-стилей. inline scripts and no inline styles.
- **Шифрование бэкапа и экспорта — опция, а не умолчание.** Галочка снята — - **Encrypting backups and exports is an option, not the default.** With the
файл скачивается открытым, как в 1.0. Иначе оператор, у которого нет места checkbox cleared the file downloads in the clear, as in 1.0. Otherwise an
для хранения пароля, потерял бы возможность сделать бэкап вообще, а operator with nowhere to keep a password would lose the ability to take a
безвозвратно нерасшифровываемый архив хуже незашифрованного: пароль SelfPost backup at all, and a permanently undecryptable archive is worse than an
не хранит. Триггером сделать шифрование обязательным считать появление unencrypted one: SelfPost does not store the password. The trigger to make
второго администратора (тогда «кто скачал» перестаёт быть одним человеком). encryption mandatory is a second administrator (at which point "who
- **Строка журнала, оставшаяся без delivery-строк, закрывается как `bounced`, а downloaded it" stops being one person).
не как есть.** Риск «вечный `queued`» снят: `mail.log` переехал в - **A journal row left without delivery lines is closed as `bounced` rather
`/data/log/` и переживает пересоздание контейнера, а log-tailer сохраняет than left as it is.** The "forever `queued`" risk is gone: `mail.log` moved to
позицию чтения (`logtail_state`, миграция `0003`), так что после старта хвост `/data/log/` and survives container recreation, and the log tailer keeps its
дочитывается. Остаток — строки, delivery-строки которых потеряны read position (`logtail_state`, migration `0003`), so the tail is read after a
безвозвратно (лог провернулся дальше 14 файлов, пока панель лежала, либо был start. What remains are rows whose delivery lines are lost for good (the log
удалён): сверка с `postqueue -p` видит, что письма в очереди нет, и через rotated past 14 files while the panel was down, or was deleted): the
2 минуты grace ставит `bounced`. Если письмо на самом деле ушло, статус reconciliation against `postqueue -p` sees the message is not in the queue and
окажется ложно-отрицательным. Принято сознательно: доставка, которую панель after a 2-minute grace marks it `bounced`. If the message did in fact go out,
не может подтвердить, не должна показываться как подтверждённая, а вечный the status is a false negative. Accepted deliberately: a delivery the panel
`queued` не отличим от «висит прямо сейчас». Сверка не срабатывает, пока cannot confirm must not be shown as confirmed, and a permanent `queued` is
tailer не дочитал лог до конца, и не трогает ничего, если `postqueue` не indistinguishable from "in flight right now". Reconciliation does not run
читается. См. [architecture.md](architecture.md) § Log tailer. until the tailer has read the log to the end, and touches nothing if
- **Доступ к `mail.log` из-под непривилегированной панели.** Каталог `postqueue` is unreadable. See [architecture.md](architecture.md) § Log
`/data/log``2750 postfix:selfpost`, файл — `0640`: пишет `postlogd` tailer.
(пользователь `postfix`), читает панель по общей группе `selfpost`, миру файл - **Access to `mail.log` from the unprivileged panel.** The `/data/log`
недоступен. Лог содержит envelope-адреса и IP клиентов, но не тела и не directory is `2750 postfix:selfpost` and the file is `0640`: `postlogd` (user
заголовки писем; в бэкап он не попадает (`log/` исключён), чтобы выгрузка `postfix`) writes, the panel reads through the shared `selfpost` group, and
оставалась состоянием, а не диагностикой. the file is inaccessible to others. The log holds envelope addresses and
client IPs, but neither message bodies nor headers; it is excluded from
backups (`log/` is skipped) so that a dump stays state rather than
diagnostics.
## ADR: CSRF через проверку Origin, без токенов ## ADR: CSRF via origin checking, without tokens
**Контекст.** Панель — формы (`POST`) с cookie-сессией; классическая CSRF- **Context.** The panel is forms (`POST`) with a cookie session — the classic
поверхность. Нужен способ отличить запрос со страницы панели от запроса, CSRF surface. What is needed is a way to tell a request from the panel's own
инициированного сторонним сайтом в браузере залогиненного админа. page apart from one initiated by a third-party site in the logged-in
administrator's browser.
**Решение.** `originAllowed` в **Decision.** `originAllowed` in
[internal/web/security.go](../internal/web/security.go) сверяет `Sec-Fetch-Site` [internal/web/security.go](../internal/web/security.go) checks `Sec-Fetch-Site`
(если браузер его шлёт) либо `Origin` (fallback) с хостом панели; запрос без (when the browser sends it) or `Origin` (fallback) against the panel's host; a
обоих заголовков **пропускается**, а не отклоняется. Токенов, привязанных к request carrying neither header is **allowed through** rather than rejected.
сессии и встроенных в формы, нет. There are no session-bound tokens embedded in forms.
**Почему не токены.** Панель однопользовательская (один администратор на **Why not tokens.** The panel is single-user (one administrator per instance) —
инстанс) — модель угроз не включает межпользовательский CSRF внутри самой the threat model does not include cross-user CSRF inside the panel itself, only
панели, только внешний сайт, заставляющий браузер админа отправить запрос. an external site making the administrator's browser send a request. The origin
Origin-проверка закрывает это без изменения ни одного шаблона: токен потребовал check covers that without touching a single template: a token would need a
бы скрытого поля примерно в двух десятках форм и синхронизации при каждой hidden field in roughly two dozen forms and synchronisation with every new form,
новой форме, а от XSS внутри панели токен всё равно не защищает — код, and it would still not protect against XSS inside the panel — code executing in
исполняющийся в origin панели, читает токен и отправляет запрос сам. От XSS the panel's origin reads the token and sends the request itself. XSS is handled
защищают автоэкранирование `html/template` и CSP, поэтому это отдельная линия by `html/template` auto-escaping and CSP, so that is a separate line of defence,
обороны, не CSRF-токен. not a CSRF token.
**Компромисс.** Клиент, не посылающий ни `Sec-Fetch-Site`, ни `Origin` **Trade-off.** A client that sends neither `Sec-Fetch-Site` nor `Origin` (a
(по-настоящему старый браузер или webview с замороженным движком), остаётся genuinely old browser, or a webview with a frozen engine) stays vulnerable — see
уязвим — см. «Принятые риски» выше. Это осознанный выбор в пользу не ломать "Accepted risks" above. This is a deliberate choice not to break the panel in
панель в таком клиенте ценой узкой остаточной поверхности. such a client, at the price of a narrow residual surface.
**Пересмотр, если:** появится требование защиты, не зависящей от поведения **Revisit if:** a requirement appears for protection that does not depend on
браузера, или панель станет многопользовательской. browser behaviour, or the panel becomes multi-user.
## Как этот список пополняется ## How this list grows
Предрелизная проверка на уязвимости (модель Fable; история — CHANGELOG The pre-release vulnerability review (history — CHANGELOG `[0.5.0]` Security)
`[0.5.0]` Security) закрывает каждую находку одним из двух способов: правка до closes every finding in one of two ways: a fix before the tag, or an entry here
тега — либо запись сюда, с обоснованием и условием возврата, как у пунктов выше. with its rationale and its condition for revisiting, like the items above.
Третьего варианта («посмотрели и ладно») нет. There is no third option ("we looked at it and moved on").
+1 -2
View File
@@ -12,8 +12,7 @@ import (
// SASLDB manages the Cyrus SASL account database (sasldb2) the panel maintains // SASLDB manages the Cyrus SASL account database (sasldb2) the panel maintains
// for application credentials (architecture.md § Mail path). The panel is the // for application credentials (architecture.md § Mail path). The panel is the
// only writer; Postfix reads it to authenticate SMTP clients. Accounts are // only writer; Postfix reads it to authenticate SMTP clients. Accounts are
// created and removed with the standard saslpasswd2 tool ("эквивалент // created and removed with the standard saslpasswd2 tool.
// saslpasswd2", per the plan).
type SASLDB struct { type SASLDB struct {
path string // sasldb2 file, under /data so it survives restarts path string // sasldb2 file, under /data so it survives restarts
realm string // SASL realm, so lookups match what Postfix's SASL uses realm string // SASL realm, so lookups match what Postfix's SASL uses