openwrt-iac / uapi / docs / 3.5.0 / uapi security model

uapi security model

What uapi defends against, what it doesn't, and what the operator should do.

Threat model

In scope (defended)

  1. Anonymous remote access. Every endpoint except /healthz, /openapi.json, and /schema* requires a bearer token. There is no anonymous read path on user resources.
  2. Plain-HTTP credential leak. TLS is mandatory for every non-localhost request. A non-TLS request from a non-loopback source returns 403 tls_required before auth runs.
  3. Token guessing. Tokens are 128 random bits (32 hex chars). Server stores sha256(salt || ":" || token); the cleartext is shown to the operator exactly once at creation. A linear scan through the token store on each request is acceptable: tokens are few, hashes are fast, and compromising the server's /etc/config/uapi exposes only hashes.
  4. Privilege escalation via HTTP token-mint. POST /tokens is gated by uapi:tokens:rw, AND the requested scopes must be covered by the caller's own, equal or narrower - escalation returns 403 scope_escalation_blocked. A compromised low-privilege token cannot mint an admin token over the API.
  5. Stolen-token reuse from elsewhere. Optional allowed_cidrs on a token pins it to a source CIDR list; requests from outside return 401 invalid_token. Optional expires_at makes leaked tokens automatically expire.
  6. Audit log tampering during compromise. Each write emits a syslog NOTICE line carrying request_id + token name + path. Forwarding syslog to a remote collector (log_ip in /etc/config/system) is the recommended production setup; a local-only log is destroyable by anyone who roots the box.
  7. Bypassing scope checks via /raw/. /raw/<package>/<id> requires BOTH a raw:*:rw|ro scope and the matching domain scope independently. A token with raw:rw but only firewall:ro cannot use /raw/firewall/... to mutate firewall sections.
  8. Shell metacharacter injection. Every shell-invoked path (apk install, init-script reload) validates names against ^[A-Za-z0-9_-]+$ (or ^[A-Za-z0-9_+][A-Za-z0-9_+.-]*$ for packages) before interpolating, and uses -- to separate flags from positional arguments. Service names from ucitrack are validated before interpolating into /etc/init.d/<svc>. The WireGuard apply path in src/lib/wg.uc builds each wg and ip command as an argument list, and one function quotes every argument with shellquote, because the restore after a failed write reads peers straight from uci, where a value never passed validate(). wg.uc also checks the values before it runs a command. A value that uapi stores for a daemon is a separate path, because the daemon or its scripts read it later. See Values that a daemon reads later.
  9. Replay attacks on POST under network flakiness. Idempotency-Key caches the response for 24 h; a network-blipped retry returns the cached response, not a duplicate side effect. Same key with a different body returns 409 idempotency_key_conflict - a request was reused for an unrelated payload.
  10. Resource exhaustion via flood. Per-token rate limit returns 429 too_many_requests with Retry-After. Default is 100/s burst 200 per token; tunable via /etc/config/uapi.
  11. Bridge-vlan self-lockout. Surfaced in the project memory: writing bridge-vlans on br-lan of the management bridge bricks the router. Use a throwaway bridge for tests; never POST bridge_vlans on the management bridge.
  12. uhttpd self-lockout. uhttpd/instances validate refuses any PATCH or PUT on the main instance that would strip uapi's own ucode_prefix entry - returning 422 conflict instead of leaving uapi unreachable.
  13. Network self-lockout. Advisory rather than a refusal, because unlike item 12 there is a legitimate version of the write: renumbering the management VLAN or moving to an out-of-band path. A network/interfaces write that moves the inbound interface's disabled, proto, ipaddrs or netmask returns X-Mgmt-Path-Warning, and so does a network/devices or network/bridge_vlans write naming the caller's device or the bridge it is a port of. GET /diagnostics reports management_path so a caller can check before writing. Firewall lockout is deliberately not covered: it would need fw4 ordering modelled, and the requesting connection survives the reload by design, so uapi cannot detect it by observation either. See docs/operations.md.

Out of scope (not defended)

  1. Local root compromise. uapi runs inside uhttpd, which runs as root. An attacker with root on the box already has uci access; the API is a wrapper. We do not defend against in-process attacks once the workload ID is admin.
  2. Fine-grained side channels. The hash compare in auth is constant-time (byte-XOR-accumulate via values.constant_time_equals) and the authorize loop iterates every token regardless of where the match occurs, so the dominant timing channel is closed. Pre-match work (the t.salt == null || t.hash == null skip, hash-function runtime itself) and downstream paths (expiry check, CIDR match, scope lookup) are not constant-time. A determined attacker with low-latency local access could in principle still extract bits, but tokens are 128 random bits and the rate limit + audit log make recovery infeasible in practice.
  3. DoS by sustained legitimate traffic. The rate limit guards per token; the request budget is per uhttpd worker / kernel limits. A determined operator who hands out 10,000 tokens at 100/s each can saturate the box. Don't.
  4. Compromise of the OpenWrt host network. If the router's management interface is on a hostile network, no application-layer auth helps. Use uhttpd's TLS + allowed_cidrs + firewall rules to restrict the listen surface.

Scope model

Hierarchical, deepest-match wins. Syntax: <segment>[:<segment>...]:(rw|ro).

Scope examples

Caller scopes Allowed Denied
*:rw every endpoint nothing
*:ro every GET every write
firewall:rw every firewall endpoint (zones/rules/redirects) network/*, dhcp/*, system
firewall:rules:rw firewall/rules CRUD firewall/zones, firewall/redirects
firewall:*:ro every GET under firewall subresources bare firewall:rw, firewall/* writes
firewall:rw + network:ro firewall CRUD + network read network writes
raw:firewall:rw + firewall:ro none of /raw/firewall/... writes (raw needs BOTH) nothing escalated
uapi:tokens:rw mint new tokens whose scopes ⊆ caller's mint tokens that escalate

Scopes that grant root

Some write scopes let the holder run code as root directly, or choose a file that a root daemon writes. Grant each one as if it were *:rw:

The list is not complete: several uci options name a script that a daemon runs as root. A parent scope includes them, so system:rw grants the first three. Deepest match wins, so system:rw with system:cron_jobs:ro keeps the system writes and denies cron writes.

One read scope deserves the same care. system:cron_jobs:ro, and every scope above it up to *:ro, returns each root crontab command in full, and a command can carry a credential. Keep secrets in a 0600 file that the command reads, rather than on the crontab line.

Values that a daemon reads later

An init script copies some stored values into a daemon's config file or into a shell command without quoting, and root reads the result. In the curated values that an audit for 3.2.0 found, uapi refuses the characters that end the line or the argument, so that a value cannot add a directive, a command or a command argument. The check runs when a write goes through uapi, so a value that LuCI, uci or another writer stored stays until a write replaces it.

/raw/ checks a value only for what uci can store, never for what a daemon reads. raw:<package>:rw with a domain scope of that package counts as a root scope for each package that a root daemon or script reads.

uapi checks the dnsmasq config after a reload with dnsmasq --test, as root and outside the jail that procd gives dnsmasq, so a conf-script in that config runs there too. Only raw:dhcp:rw with a domain scope of dhcp, a root scope already, can write such a line.

Audit consequence

The token name is logged on every audit line. Tokens should be named for their owner (ci_bot, terraform_prod, alice_laptop) so the audit log identifies the responsible party, not a hash.

Authentication-design exclusions

uapi defends the surface above with bearer tokens deliberately, not by accident. Two design candidates that would seem natural but are explicitly rejected:

Both could be added without breaking the wire surface (new endpoints are non-breaking). The deliberate exclusion is to keep the security model auditable as "the set of tokens in /etc/config/uapi" with no second authentication path to reason about.

Public endpoints

Three endpoints skip the bearer-token requirement:

All three still pass the TLS check; only the bearer requirement is waived. Plain HTTP from a non-loopback source still returns 403 tls_required before the public-endpoint short-circuit runs.

uapi reads and parses the body of a POST, PUT or PATCH before the bearer check, on every path. json() takes about 1.6 KB for each object or array, so 1 MiB of [{},{},...] took 560 MB. A body over 256 KiB, sent with a Content-Length or chunked, or a body with more than 2000 { and [ characters, answers 413 payload_too_large before the parse, which keeps the parse of a body without a token under about 13 MB (measured with ucode 2026.01.16 on x86_64). A Content-Length that uapi does not read as a whole number from 0 to 262144 answers 413 too, because uhttpd reads such a value in another way: on a 64-bit router it wraps a value of 2^32 or more. uhttpd hands a chunked body over de-chunked and with no Content-Length, and uapi reads it until uhttpd closes the pipe after the last chunk. uapi joins the parts of a body as it reads them, so a body that arrives a byte at a time takes about as much memory as one that arrives whole.

uhttpd parses what the request process leaves unread as the next request on the connection. So before it answers, on every path and the public endpoints included, uapi reads and drops what is left of every body that uhttpd hands over. uhttpd does not hand over some bodies whole, and uapi cannot drop what follows them: uhttpd ends a chunked body at a chunk extension, parses a trailer after the last chunk as a new request, and reads a Transfer-Encoding value other than chunked in lower case, such as Chunked, as no body.

A body has to arrive in full within 10 s of the start of the request process. uhttpd hands it over a blocking pipe, where a process that waits for a body that does not come holds one of the max_requests of uhttpd, 3 by default and shared with LuCI, until the script timeout of uhttpd, 60 s by default. uapi makes the pipe non-blocking with ucode-mod-io. So a POST, PUT or PATCH whose client declares a body and sends less, sends it too slowly, or does not send the last chunk of a chunked body, gets 400 bad_request after about 10 s, before the bearer check, and syslog gets a uapi-body-deadline line (docs/operations.md). The drop of what is left of a body stops at the same deadline. So a request that answers without reading its body gets its normal answer 10 s after it started when that body does not arrive, and logs the same line: a 413, a POST to /healthz, or a GET or DELETE with a declared body. A DELETE has then already been applied. uapi checks the deadline when it finds the pipe empty, so that a drop after a write that took longer still reads a body that has arrived. A body that keeps arriving faster than uapi drops it is therefore bounded by its Content-Length or its last chunk and by the script timeout, not by the deadline. The deadline bounds each request, not how many a client opens one after another. Without ucode-mod-io, uapi reads a body from the blocking pipe with no deadline, and logs that once when uhttpd starts.

uhttpd keeps the connection open after every answer of the handler, and nothing that uapi sends makes it close the connection. After a body that missed the deadline, uhttpd parses what the client sends next on the connection, the rest of that body included, as a new request, and answers it. For a client on its own connection this changes nothing that it could not do with a request of its own. It matters behind a reverse proxy that streams request bodies to uhttpd and reuses its connections to uhttpd for other clients: the rest of a late body would reach uhttpd as a request, and its answer would go to the request that the proxy sends next on that connection. Such a proxy should buffer each request body before it forwards it, as nginx does by default, or close a connection to uhttpd on which it did not finish sending a request.

TLS posture

Token storage

/etc/config/uapi token sections:

config token 'ci_bot'
    option salt 'a1b2c3d4...'
    option hash 'e5f6...sha256-of-salt-colon-token'
    list scopes '*:rw'
    option expires_at '1733000000'             # optional
    list allowed_cidrs '10.0.0.0/8'             # optional
    option last_used_at '1732999900'            # tracked
    option last_used_ip '10.0.0.42'             # tracked

The salt+hash design defends against an offline attacker who reads the token store. The hash + 16-char salt makes any pre-computed rainbow attack useless and forces a per-token bruteforce; the token's own 128 bits make that intractable.

Rate limit guarantees (and non-guarantees)

Audit shape

One syslog line per write at NOTICE:

uapi <request_id> <token_name> AUDIT - <method> <path> <status> [<duration_ms>ms]

One syslog line per 401/403/5xx at WARNING/ERROR:

uapi <request_id> <token_name|-> WARN <code> <method> <path> <status> [<duration_ms>ms]
uapi <request_id> -             ERROR <code> <method> <path> <status> [<duration_ms>ms]

One syslog line per insecure-bypass request at NOTICE:

uapi-insecure-bypass <request_id> <method> <path> status=<n> remote=<addr>

Recommendations for hardened deployments

  1. Configure persistent syslog (log_file in /etc/config/system). The default ringbuffer is volatile.
  2. Forward syslog to a remote collector (log_ip). A locally-only audit log is destroyable by anyone who roots the box.
  3. Use NTP. Audit timestamps are useless if the clock is wrong. /healthz reports time_sync: ok when uptime > 60s AND current epoch > 1700000000 (a sanity floor), unknown for the first 60 seconds after boot, and degraded once past that with the epoch still below the floor.
  4. Pin tokens to source CIDRs. allowed_cidrs defends against token theft from outside the management network. Prefixes of either family are accepted and a list may mix them. A caller is matched only against entries of its own family, so on a dual-stack router 0.0.0.0/0 alone still denies every IPv6 caller; "any address" means listing both 0.0.0.0/0 and ::/0. That asymmetry is deliberate: an allowlist that silently widened to a second address family would be a worse failure than one that denies.
  5. Set token expiry. --expires-in 90d on every minted token forces rotation. The HTTP rotation endpoint (POST /tokens, which takes expires_in_seconds) makes this ergonomic from automation.
  6. Use mutual TLS for service-account workloads (CI, Terraform). It's an independent factor on top of bearer auth and prevents a stolen bearer from being replayed without the cert.

What lands in syslog

The audit lines above. The standard error envelope's message field is human-readable English and may name specific failing fields ("src_zone is required") - never sensitive values.

Specifically NOT logged: - Cleartext token values. - Cleartext passwords (the system/password endpoint audit-logs the user name and request id, never the password). - TLS certificate or key material.

Reporting issues

Do not file a security issue as a public GitHub issue. Use GitHub's private vulnerability reporting, linked from SECURITY.md, which also sets out what counts as a vulnerability in a daemon that is root-privileged by design, and which of the decisions above are recorded choices rather than defects.