docs(security): rewrite the OSS Scanner threat model against the current code

The model predated several boundaries the scanner should test. It listed only
the monitor and node-sync token scopes, so node-admin, the three route
allowlists and the mTLS-certificate identity were unstated, and it never named
validatePushedInbound, the guard that keeps a node-sync push away from the
receiving host's files and sockets. The MCP endpoint, the public sponsor
routes, the pre-auth listener code, the LDAP login path and the subscription
headers persisted into client_hwids were missing as entry points.

It now states the default configuration a finding may assume, splits each
attacker into the routes and files that serve them, covers third-party content
the panel fetches, and rates end-user limit evasion and revoked-client access
in the severity rubric. The exercise section names each fuzz target's package
and how to mint a restricted token on a live panel.
This commit is contained in:
Sanaei
2026-11-29 23:33:09 +03:30
parent 2bf368e4c1
commit 6171245fb1
+272 -82
View File
@@ -1,117 +1,307 @@
# 3x-ui threat model
## What this project does and why it matters
3x-ui is a self-hosted web control panel for Xray-core. One Go binary stores
inbounds, clients and settings in SQLite (default) or PostgreSQL, renders an
Xray JSON config from that state, supervises Xray-core and the `mtg-multi`
MTProto sidecar as child processes, runs AmneziaWG and TUIC servers in-process,
and serves an embedded React SPA. It is deployed on internet-facing VPS hosts,
usually as root, often in censored regions where a compromise exposes the
people relying on the proxy. Read `docs/architecture.md` in the scanned revision
for the code map; do not assume package names stay fixed.
and serves an embedded React SPA. A second HTTP server hands subscription
configs to end users.
## Trust boundaries and attackers
It runs on internet-facing VPS hosts, usually as root, often in censored
regions. A compromise exposes the proxy credentials, IP addresses and traffic
metadata of the people relying on it, and gives root on the host. Operators
commonly sell access, so they hand subscription links, proxy credentials and
bot access to people they do not trust.
Trusted: the panel administrator (one account, or an admin-scope API token).
The admin can already edit the full Xray config, run a panel update, import a
database and set file paths, so admin-to-root is by design and out of scope.
Read `docs/architecture.md` in the scanned revision for the code map. The
paths below are starting points; do not assume they stay fixed.
Untrusted, in decreasing order of importance:
## Default configuration
1. **Unauthenticated network attacker** reaching the panel port (default 2053)
or the subscription port. Login (`POST /login`, 2FA, LDAP), CSRF/session
handling (`internal/web/session/`), the login rate limiter
(`controller/login_limiter.go`), the `checkAPIAuth` gate in
`controller/api.go` (session, Bearer token, mTLS client cert),
`/csrf-token`, PWA/static routes, and the WebSocket `/ws` upgrade.
2. **Subscription end users.** They know only their own `subId` and fetch
`{subPath}/{subId}`, the JSON/Clash/Mihomo variants and `hwid-status`
(`internal/sub/`). Each must see only their own clients; check subId
guessing, cross-client leakage, header injection, forwarded-header trust
(`internal/sub/forwarded_trust.go`) and the public subscription page.
3. **Limited API tokens.** `monitor` and `node-sync` scopes are restricted by
explicit allowlists in `controller/api.go` (`enforceTokenScope`). Any way
for such a token to reach a route outside its allowlist is a vulnerability.
4. **Master/node peers.** A master panel drives child nodes over HTTPS
(`internal/web/runtime/`, TLS modes verify/skip/pin/mtls). A compromised
or malicious node must not gain control of the master or of other nodes;
node responses (inbound lists, traffic, online clients, certificates,
`descendants`) are untrusted input on the master.
5. **Proxy traffic.** Packets reaching AmneziaWG (`internal/amneziawgnet/`),
TUIC (`internal/tuic/`) and the loopback SOCKS5 relays into Xray. A peer
must not escape its per-peer auth, reach another peer's traffic, or crash
the panel process.
6. **Chat-bot users.** Telegram and Discord bot messages and callback data
(`internal/web/service/tgbot/`, `discord/`). Non-admin chats may only see
their own client (bound via the subId invite token); admin commands must
be unreachable from them.
7. **Imported content** an admin may receive from a third party: share links
and subscription URLs parsed by the import paths (`FuzzParseLink`), and
geosite/geoip `.dat` files (`internal/xray/geodata/`).
Assume these unless a finding states otherwise. A finding that needs a
non-default setting is valid, but must name the setting.
Also in scope: stored or reflected XSS in the SPA or the subscription page
from client remarks, emails, inbound tags or any other value a non-admin can
influence; SQL injection through GORM raw queries; path traversal in file or
certificate handling; secrets leaking into logs, subscription output, API
responses for limited tokens, or node sync payloads.
- Panel: port 2053, base path `/`, plain HTTP until the admin sets a
certificate. The first user gets a random username and password, printed
once at first start. 2FA, LDAP login, node mTLS and the MCP endpoint are off.
- Subscription server: on, port 2096, each of the raw, JSON and Clash paths a
random 16-character segment. JSON and Clash output, and their User-Agent
auto-detection on the raw route, are off.
- Telegram, Discord, email and WeChat notifiers are off.
- Forwarded headers (`X-Forwarded-For`, `X-Real-IP`) are trusted only from
`trustedProxyCIDRs`, default loopback.
- The default Xray template listens for its gRPC API on `127.0.0.1:62789` and
blackholes `geoip:private` destinations.
- An unauthenticated `/panel/api/*` request answers 404, not 401, unless it
carries a `Bearer` header or `X-Requested-With: XMLHttpRequest`.
## Trust boundaries
**Trusted: the panel administrator** — the logged-in session, or an API token
of scope `admin`. The admin can edit the full Xray config, update the panel,
import a database, choose file paths and enable every integration, so
admin-to-root is by design and out of scope.
Everyone below is untrusted, in decreasing order of importance.
### 1. Unauthenticated network attacker on the panel port
Reachable without credentials: `GET {base}/` (login page), `/csrf-token`,
`/sponsors`, `/sponsors/logo/:name`, `POST /login`, `/logout`,
`/getTwoFactorEnable`, the PWA files (`/manifest.webmanifest`,
`/service-worker.js`, `/pwa-register.js`, `/icons/:name`), `/assets/*`, and
the refusal paths of `/ws`, `/panel/*` and `/panel/api/*`.
- Authentication: `controller/index.go` (`login`), `service/panel/user.go`
(bcrypt, TOTP, optional LDAP bind where the submitted username reaches an
LDAP filter), `session/` (signed cookie, `LoginEpoch` invalidation, CSRF
token), `controller/login_limiter.go`.
- The API gate: `checkAPIAuth` then `enforceTokenScope` in
`controller/api.go`, then `middleware.ConfigEnvelopeMiddleware` (zstd body
+ SHA-256 header, decoded before the handler) and `CSRFMiddleware`.
- Listener code that parses bytes before any auth:
`internal/web/network/` (auto-HTTPS sniffing, connection limits),
`middleware/` (body limit, domain validator).
- Client-address spoofing: `getRemoteIp` (`controller/util.go`) feeds the
login limiter, the logs and the login notifications.
- The submitted username is copied into the log file and into Telegram,
Discord, email and WeChat login notifications.
- `/ws` accepts a session cookie only and checks `Origin` itself
(`controller/websocket.go`).
### 2. Subscription users, and anyone who can reach the subscription port
A subscriber knows only their own `subId`, which is the bearer secret for
`{subPath}/{subId}`, `{subPath}/{subId}/hwid-status`, the JSON, Clash, Mihomo
and legacy Clash variants, and the HTML subscription page (`internal/sub/`).
- Each subscriber must see only their own clients. Check subId guessing or
enumeration, timing or status differences that confirm a subId, and
cross-client leakage through shared inbounds, hosts, external links or
caches.
- Request headers are attacker-controlled and partly persisted: `X-HWID`,
`User-Agent`, `X-Device-OS`, `X-Ver-OS` and `X-Device-Model` land in
`client_hwids` and are shown to the admin. `User-Agent` also selects the
output format through admin-set regular expressions.
- The subscription page injects JSON into an inline `<script>`
(`serveSubPage` in `sub/controller.go`); client remarks, emails and the
announce text end up there.
- Response headers are built from stored values (`Profile-Title`,
`Announce`, `Support-Url`, `Routing`, `Content-Disposition`): check header
injection through any part a non-admin or an external provider controls.
- `sub/forwarded_trust.go` decides when forwarded host and scheme headers may
shape the links returned.
- HWID device limits (`hwid_rejection.go`) and the opt-in rate limiter
(`rate_limiter.go`): bypasses, and memory growth under many identities.
### 3. Restricted API tokens
Scopes are `monitor`, `node-sync`, `node-admin` and `admin`
(`model.ApiScope*`). The first three are held to explicit route allowlists in
`controller/api.go` (`monitorScopeAllow`, `nodeSyncScopeAllow`,
`nodeAdminScopeAllow`), matched on the Gin route pattern and method.
- Any route outside its allowlist reachable by such a token is a
vulnerability, including through `POST /panel/api/mcp` (off by default),
whose tools re-enter the router with the caller's own headers
(`internal/web/mcp/`). The `call_api` tool must not reach a route the same
credentials could not call directly.
- A verified mTLS client certificate authenticates as `node-sync`; only a
valid `node-admin` bearer raises it. A certificate must never yield `admin`.
- `monitor` must expose no secrets: no credentials, subscription ids, keys,
tokens or client addresses.
- `node-sync` may push inbounds and clients, but `validatePushedInbound`
(`service/inbound_push_guard.go`) must refuse every field that reaches the
receiving host's files, sockets or services. A way past that guard, such as
reading a file or binding a host-internal address, is a vulnerability.
### 4. Master and node panels
A master drives child nodes over HTTPS (`internal/web/runtime/`; TLS modes
`verify`, `skip`, `pin`, `mtls`) with a bearer token or client certificate
per node.
- A malicious or compromised node must not gain control of its master or of
other nodes. Everything it returns is untrusted on the master: inbound
lists, traffic snapshots, online clients, client IPs, certificate paths,
`descendants`, error messages. Decoding and caps are in
`runtime/remote_decode.go` and `runtime/node_snapshot_decode.go`; merging
is in `service/inbound_node.go`.
- A node must not make the master send its bearer token or client
certificate to another host (`NoCrossHostRedirect`), nor claim another
node's GUID to rewrite traffic, online state or clients it does not host.
- Misreporting traffic or online state for the clients a node itself serves
is inherent to the design and not a finding.
- In the other direction, a master holds only `node-sync` or `node-admin`
authority on a node; see section 3.
- Node bearer tokens are encrypted at rest when `XUI_NODE_TOKEN_KEY` or
`XUI_NODE_TOKEN_KEY_FILE` is set.
### 5. Proxy clients and raw proxy traffic
- Unauthenticated packets reaching AmneziaWG (`internal/amneziawgnet/`), TUIC
(`internal/tuic/`) or an MTProto port must not crash the panel process or
cost unbounded memory, goroutines or sockets before authentication.
- An authenticated proxy client must not escape its own identity: no access
to another peer's traffic, counters or loopback SOCKS5 credentials
(`socks_bridge.go`, `relay_gate.go`, `identity.go`).
- With the default Xray template, a proxy client must not reach
loopback-only control surfaces: the Xray gRPC API, the `mtg-multi`
management API (`127.0.0.1`, per-process bearer token,
`internal/mtproto/manager.go`), the AmneziaWG egress SOCKS5 server, or a
loopback-bound panel.
- A disabled, expired, over-quota or deleted client must lose access on Xray,
the sidecars and every node.
### 6. Chat-bot users
- Telegram (`service/tgbot/`): every update is classed stranger, client or
admin (`tgbot_level.go`). Commands are allowlisted per level and callbacks
from strangers are dropped. A client may only see clients bound to their
own Telegram id; the binding token is the client's subId
(`tgbot_invite.go`), with a per-user attempt limit. Check forged or
replayed callback data, group and channel senders, and any path from a
non-admin to an admin action or to another client's data.
- Discord (`service/discord/`): commands are honoured only in the configured
channel from ids in `discordAdminIds`; an empty list admits nobody.
- Values the panel did not write (client emails, remarks, login usernames,
node messages) must not break out of Markdown or HTML in bot messages.
### 7. Third-party content the panel fetches or an admin pastes
The admin chooses the source, but its operator controls the bytes and every
redirect:
- external subscription providers merged into a client's subscription
(`sub/external_subscription.go`), outbound subscriptions
(`service/outbound_subscription.go`), remote routing rules
(`sub/remote_routing.go`);
- share links and subscription bodies parsed on import
(`util/link/`, `FuzzParseLink`);
- geosite/geoip `.dat` files (`internal/xray/geodata/`);
- the sponsor list and logos fetched for the public login page
(`service/panel/sponsor.go`), served from the panel's own origin;
- PIA, WARP and NordVPN API responses (`internal/pia/`,
`service/integration/`).
Check SSRF into loopback or private addresses through redirects and DNS
(`service/url_safety.go`, `internal/util/netsafe/`), unbounded bodies and
headers, parser crashes, and provider content that reaches a subscriber's app
or the admin's browser as something other than data.
### Vulnerability classes in scope everywhere
- Stored or reflected XSS in the SPA, the login page or the subscription
page from any value a non-admin controls. The panel sends a nonce-based
CSP (`middleware/security.go`); say whether the payload executes under it.
- SQL injection through GORM raw queries or dialect-specific SQL
(`internal/database/dialect.go`).
- Path traversal in certificate, geo file, template, backup or log handling.
- Secrets in logs, subscription output, restricted-token responses, bot
messages or node sync payloads: password hashes, the session secret, API
and node tokens, 2FA seeds, private keys, bot tokens.
- Races that double-apply or skip an authorization or quota decision.
## How to exercise it
- Checkout at `/src`; the panel binary is `/usr/local/bin/x-ui` (debug build),
Xray-core is `/usr/local/bin/xray`, and the sidecars and geo files are in
`/src/build/bin`.
- Checkout at `/src`. The panel binary is `/usr/local/bin/x-ui` (built with
`-N -l`), Xray-core is `/usr/local/bin/xray`, and the sidecars and geo
files are in `/src/build/bin`. `sqlite3`, `curl` and `jq` are installed.
There is no network; `GOPROXY=off` and npm is offline.
- Go tests: `cd /src && go test -count=1 ./...`. Real-DB helpers live in
`internal/database/dbtest` (`dbtest.InitDB(t, path)`); `internal/sub`'s
`initSubDB(t)` is the template for subscription tests. `httptest` is used
for HTTP. `XRAY_E2E_BINARY` is set, so the xray gRPC end-to-end tests run.
`initSubDB(t)` is the template for subscription tests; `httptest` is used
for HTTP. `XRAY_E2E_BINARY` is set, so the Xray gRPC end-to-end tests run.
- Route and scope contracts: `internal/web/routes_contract_test.go`,
`internal/web/node_contract_test.go` and
`internal/web/controller/api_auth_test.go` show how to drive the real
router with a token.
- Master + node end to end:
`go build -o /tmp/x-ui . && XUI_NODE_E2E_BINARY=/tmp/x-ui go test -count=1 -v ./internal/nodee2e/`.
- Fuzz targets: `FuzzParseLink`, `FuzzDecodeCertPin` (`go test -fuzz=...`).
- Fuzz targets (`go test -run '^$' -fuzz=<name> -fuzztime=60s <pkg>`):
`FuzzParseLink` in `./internal/util/link/`, `FuzzDecodeCertPin` in
`./internal/web/runtime/`, `FuzzParseServerList` in `./internal/pia/`,
`FuzzCountCappedList` in `./internal/util/json_util/`.
- Frontend: `cd /src/frontend && npx vitest run --project unit --project components`.
The Storybook browser project needs Chromium and is not provisioned.
- Running a live panel: `XUI_DB_FOLDER=/tmp/xui XUI_LOG_FOLDER=/tmp/xui
XUI_BIN_FOLDER=/src/build/bin x-ui` (logs a generated username and password on
first start; `x-ui setting -h` changes port, base path and credentials).
- Live panel:
`XUI_DB_FOLDER=/tmp/xui XUI_LOG_FOLDER=/tmp/xui XUI_BIN_FOLDER=/src/build/bin x-ui`.
It prints the generated username and password on first start. With the
same environment, `x-ui setting -show true` prints the port and base path,
`x-ui setting -username U -password P` sets credentials, and
`x-ui setting -getApiToken -tokenName t -tokenScope monitor` (or
`node-sync`, `admin`) mints a token. Subscription paths are in the
`settings` table of `/tmp/xui/x-ui.db`.
- Session requests with an unsafe method need the token from
`GET {base}/csrf-token` in `X-CSRF-Token`; bearer requests do not.
- Baseline logs from the image build: `/src/.oss-scanner-go-test.log` and
`/src/.oss-scanner-vitest.log`. A built image does not prove the tests passed.
- PostgreSQL is not installed: tests gated on `XUI_TEST_PG_DSN` skip, so a
green run says nothing about the Postgres dialect.
`/src/.oss-scanner-vitest.log`. A built image does not prove the tests
passed; read them before blaming a failure on a change.
- PostgreSQL is not installed. Tests gated on `XUI_TEST_PG_DSN` skip, so a
green run says nothing about the Postgres dialect. Report a Postgres-only
finding from code reading and say it was not executed.
- Telegram, Discord, LDAP and SMTP servers are unreachable. Drive those
paths through their Go tests and handler functions, not a live bot.
## Severity
- **Critical:** unauthenticated remote code execution; authentication bypass
to admin; a limited token, subscription user, bot user or node obtaining
admin control; reading the database or admin credentials unauthenticated.
- **High:** cross-client disclosure of subscription configs or credentials
without knowing the target's subId; scope escape of a `monitor`/`node-sync`
token; stored XSS that a non-admin can plant in the admin panel; a
malicious node compromising its master; SQL injection reachable by a
non-admin; peer isolation bypass in AmneziaWG/TUIC.
- **Medium:** remotely triggerable crash or resource exhaustion of the panel
process without authentication (it takes down every proxy it supervises);
CSRF on a state-changing admin action; login rate-limit bypass; secret
leakage into logs.
- **Low / informational:** issues that need admin access, local shell access,
or an attacker already able to modify the database or binaries.
to admin; a restricted token, subscription user, proxy client, bot user or
node obtaining admin control or code execution; reading the database,
admin credentials or the session secret without authentication.
- **High:** disclosure of another client's subscription config or proxy
credentials without knowing its subId; scope escape of a `monitor`,
`node-sync` or `node-admin` token, or a bypass of the push guard; XSS that
a non-admin can plant and that executes in the admin's session; a
malicious node compromising its master or another node; SQL injection or
SSRF into loopback reachable by a non-admin; peer isolation bypass in
AmneziaWG or TUIC; a proxy client reaching a loopback control surface.
- **Medium:** crash or resource exhaustion of the panel process triggered
remotely without authentication by a small number of requests (it takes
down every proxy it supervises); CSRF on a state-changing admin action;
login rate-limit or 2FA bypass; client-address spoofing that defeats a
limiter; a revoked, expired or over-quota client keeping access; injected
markup in admin views or bot messages that does not execute script;
secrets written to logs.
- **Low / informational:** subId or base-path confirmation oracles;
traffic under-counting and IP-limit or HWID-limit evasion by a valid
client; issues that need admin access, local shell access, or an attacker
already able to modify the database or binaries.
## Reports and patches
Name the scanned commit, the attacker's starting position from the list
above, the configuration needed (default or not), the entry route, and the
full path to impact. Give a deterministic reproducer, ideally a Go test in the
package that owns the bug, using the real DB helpers rather than mocks.
above, the configuration needed (default or the exact setting), the entry
route, and the full path to impact. Give a deterministic reproducer, ideally
a Go test in the package that owns the bug, using the real DB helpers and the
real router rather than mocks. Say plainly what was executed and what was
only read.
Patches should fix the root cause, follow `CLAUDE.md` in the repository
(comments at most two lines, stdlib `testing`, state-changing inbound/client
operations dispatched through `runtime.Runtime`), and include a regression
test that fails without the fix. Merge findings sharing one root cause.
operations dispatched through `runtime.Runtime`, a migration for any model
change), and include a regression test that fails without the fix. Merge
findings sharing one root cause into one report; report distinct root causes
separately even when they share a route.
## Out of scope
- Anything requiring the admin account or an admin-scope token, including
admin-supplied Xray config, custom geo files, panel update and DB import.
- Vulnerabilities inside Xray-core, mtg-multi, amneziawg-go or other
dependencies, unless 3x-ui itself makes them reachable in a way upstream
does not; report the 3x-ui path.
- `skip` TLS mode accepting any node certificate: it is an explicit,
documented opt-out.
- The `docs/` site, `tools/`, install scripts and CI workflows.
- Anything requiring the admin session or an `admin` token, including
admin-supplied Xray config, custom subscription templates, custom geo
files, panel update and database import. Admin self-XSS is out; XSS an
admin triggers by viewing a value someone else planted is in.
- Vulnerabilities inside Xray-core, mtg-multi, amneziawg-go, gVisor or other
dependencies, unless 3x-ui makes them reachable in a way upstream does
not; report the 3x-ui path.
- The `skip` node TLS mode accepting any certificate, a panel left on plain
HTTP, and LDAP `InsecureSkipVerify`: explicit, documented opt-outs.
- The secrecy of the base path or subscription path. They are obscurity,
not authentication; subId and the login are the boundaries.
- Volumetric denial of service, and exhaustion that needs sustained traffic
beyond the listener limits in `internal/web/network/`.
- Behaviour only present under `XUI_DEBUG=true`.
- The `docs/` site, `tools/`, install and management scripts, Docker files
and CI workflows.
- Missing hardening headers or cookie flags with no demonstrated exploit.