Skip to content

Commit dcceb12

Browse files
authored
Merge pull request #1 from solisoft/task/security-audit-1
chore(security): land security audit findings as SEC-001..015 tickets
2 parents 909260a + 3e13abb commit dcceb12

16 files changed

Lines changed: 744 additions & 0 deletions

‎tasks/done/security-audit-1.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# security audit
2+
3+
as a rust expert do a security audit.
4+
create tickets in tasks/todo for any security issue found
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# SEC-001 — RESP server has no read/idle timeout, enabling connection exhaustion DoS
2+
3+
**Severity:** High
4+
5+
## Location
6+
7+
- `crates/solikv-server/src/resp_server.rs:67-110` (`handle_connection`)
8+
- `crates/solikv-server/src/resp_server.rs:19` (`MAX_CONNECTIONS = 10_000`)
9+
10+
## Issue
11+
12+
`handle_connection` calls `socket.read_buf(&mut read_buf).await` (line 105) with no
13+
read timeout. A connection that sends nothing (or a partial RESP frame) sits forever
14+
in `read_buf` and holds one of the 10,000 semaphore permits.
15+
16+
A single attacker opening 10,000 idle TCP connections (no bytes ever sent) drains
17+
the connection pool and locks every legitimate client out. The pre-pubsub-mode read
18+
loop, the pubsub-mode `socket.read_buf` (line 611), and the `auth_middleware`
19+
fast-fail path all share this property: no per-stage deadline.
20+
21+
There is also no `tcp_keepalive` configuration, so half-open TCP connections are
22+
never reaped.
23+
24+
## Fix
25+
26+
1. Wrap the per-iteration `socket.read_buf(...)` calls in
27+
`tokio::time::timeout(...)` with a configurable idle deadline (suggested
28+
default: 60 s, matching Redis `timeout 0` override).
29+
2. On timeout, write a RESP error and close the connection.
30+
3. Apply the same timeout in `handle_pubsub_mode` (`resp_server.rs:611`).
31+
4. Optionally enable TCP keepalive on the accepted socket via
32+
`socket2::SockRef::from(&stream).set_tcp_keepalive(...)`.
33+
34+
## Verification
35+
36+
- Unit: open a TCP connection, send 0 bytes, assert it is closed after the
37+
configured timeout.
38+
- Manual: `nc -q -1 127.0.0.1 6379 &` ×10 000, then verify a fresh `redis-cli`
39+
client can still connect within `timeout * 2`.
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# SEC-002 — RESP parser recurses without depth limit, allowing single-packet stack overflow / crash
2+
3+
**Severity:** High
4+
5+
## Location
6+
7+
- `crates/solikv-resp/src/codec.rs:227-269` (`decode_array`, recursive call to `decode_frame`)
8+
- `crates/solikv-resp/src/codec.rs:131` (`MAX_ARRAY_LEN = 1_048_576`)
9+
10+
## Issue
11+
12+
`decode_array` calls `decode_frame(&src[offset..])` for every element, and
13+
`decode_frame` dispatches back to `decode_array` for nested arrays
14+
(`*` prefix). There is no recursion-depth limit. An attacker connected to the
15+
RESP port can send a single buffer containing `*1\r\n*1\r\n*1\r\n…` repeated a
16+
few thousand times. Each level adds a stack frame, and the recursion eventually
17+
overflows the (default 2 MB) thread stack — the Tokio worker dies with SIGSEGV
18+
and the server's connection accept loop on that worker is gone.
19+
20+
This is *pre-auth* (the parser runs before AUTH is checked) and unauthenticated
21+
remote callers can crash the server with a single TCP packet. `MAX_ARRAY_LEN`
22+
limits each level's element count but does not bound nesting depth.
23+
24+
## Fix
25+
26+
1. Add a `decode_frame_with_depth(src, depth)` helper. Bump `depth` on each
27+
recursive call from `decode_array`. Reject (return `Err`) when `depth`
28+
exceeds a hard cap (suggested: 32, matching Redis client/server typical
29+
nesting use).
30+
2. Change the public `decode_frame(src)` to call
31+
`decode_frame_with_depth(src, 0)`.
32+
3. Add a unit test that constructs an N-deep nested array (e.g. 10 000) and
33+
asserts the parser returns an error rather than panicking / overflowing.
34+
35+
## Verification
36+
37+
- Unit: deep-nested input returns `Err`, not a stack overflow.
38+
- Existing parser tests still pass.
39+
- `cargo clippy --quiet -- -D warnings` clean.
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# SEC-003 — Lua VM is pooled and reused without resetting global state, allowing sandbox poisoning across scripts
2+
3+
**Severity:** High
4+
5+
## Location
6+
7+
- `crates/solikv-engine/src/lua.rs:103-138` (`LUA_POOL`, `take_lua`, `return_lua`)
8+
- `crates/solikv-engine/src/lua.rs:147-186` (`execute_script`)
9+
- `crates/solikv-engine/src/lua.rs:192-209` (`sandbox_lua` runs once on cold path only)
10+
11+
## Issue
12+
13+
`take_lua` reuses a previously-sandboxed `Lua` instance from a thread-local
14+
`LUA_POOL`. The sandbox (`sandbox_lua`) is applied once on creation, and only
15+
`KEYS` / `ARGV` are reset between invocations. Globals other than `KEYS` /
16+
`ARGV` — including the standard-library tables `string`, `table`, `math` —
17+
are *not* restored between scripts.
18+
19+
A malicious script can therefore plant traps that affect future scripts running
20+
on the same worker thread:
21+
22+
```lua
23+
-- attacker: EVAL "string.byte = function() return 999 end ..."
24+
-- victim: EVAL "return string.byte('x')" → 999, not 120
25+
```
26+
27+
Or worse, a script can monkey-patch `redis.call` itself:
28+
29+
```lua
30+
local orig = redis.call
31+
redis.call = function(...) ... return "" end -- silent data corruption
32+
```
33+
34+
Because the VM is pooled per-thread and reused, this contaminates other tenants
35+
sharing the server. `redis` itself is set in `setup_redis_module` only on cold
36+
path (line 124), so a poisoned `redis.call` survives every subsequent
37+
`execute_script` on that thread until the VM is dropped (pool is full).
38+
39+
## Fix
40+
41+
Either (preferred):
42+
43+
1. Re-snapshot the global table after `sandbox_lua` + `setup_redis_module`
44+
completes (e.g., serialize a registry-stashed clean copy), and restore it on
45+
each `take_lua`. mlua exposes `Lua::globals()` and `Table::clear()` /
46+
pairs traversal to rebuild it.
47+
48+
Or, simpler:
49+
50+
2. Drop the pool entirely — create a fresh `Lua` per script. The cost is one
51+
sandbox setup per EVAL, which dominates only for trivially small scripts.
52+
Benchmark first.
53+
54+
Or:
55+
56+
3. Wrap user scripts in a fresh Lua function environment (`setfenv` /
57+
`_ENV` swap in 5.2+) so each script gets its own `_ENV` with read-only
58+
parent. Verify mlua exposes the necessary primitives.
59+
60+
Option 1 or 3 preserves the perf benefit. Option 2 is simplest and safest.
61+
62+
## Verification
63+
64+
- New test: run two scripts back-to-back on the same engine; the first mutates
65+
`string.byte`, the second calls `string.byte('x')` and must observe the
66+
original value.
67+
- Existing Lua tests still pass.
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# SEC-004 — Script cache (`SCRIPT LOAD` / `EVAL`) has no size cap, enabling memory-exhaustion DoS
2+
3+
**Severity:** High
4+
5+
## Location
6+
7+
- `crates/solikv-engine/src/lua.rs:20-58` (`ScriptCache`)
8+
- `crates/solikv-engine/src/dispatch.rs:3236` (`EVAL` calls `script_cache.load(script)` on every invocation)
9+
- `crates/solikv-engine/src/dispatch.rs:3286-3303` (`SCRIPT LOAD`)
10+
11+
## Issue
12+
13+
`ScriptCache` is a `DashMap<String, String>` with no eviction, no maximum
14+
entry count, and no maximum source size. Any authenticated client can call:
15+
16+
```
17+
SCRIPT LOAD "<random 1 MiB script body>"
18+
```
19+
20+
repeatedly, and each insert is permanent. With ~1 KiB scripts the server holds
21+
~10 MB after 10 000 calls; with 1 MiB scripts, 10 GB after 10 000 calls. There
22+
is no command to flush only stale entries, and even `SCRIPT FLUSH` requires the
23+
attacker's cooperation.
24+
25+
`EVAL` *also* re-inserts the script source on every execution (line 3236), so
26+
the cache grows on the regular EVAL hot path too — not just on `SCRIPT LOAD`.
27+
28+
## Fix
29+
30+
1. Cap script source size at a sane limit (suggested: 64 KiB, configurable).
31+
Reject larger scripts with `ERR script too long`.
32+
2. Cap total script count (suggested: 8 192 entries) and switch the storage
33+
from `DashMap` to a small LRU (e.g. `lru::LruCache` behind a `Mutex`,
34+
contention is fine — script load is rare).
35+
3. In `EVAL`, only insert into the cache if the SHA is not already present
36+
(cheap `contains_key` check), to avoid the rewrite-on-every-execution
37+
churn.
38+
39+
## Verification
40+
41+
- Unit: load N scripts where N > cache cap, assert oldest is evicted.
42+
- Unit: `EVAL` of an oversize script returns `ERR script too long`.
43+
- Existing scripting tests still pass.
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# SEC-005 — Passwords accepted only via CLI flags, exposing them in `ps` / `/proc/<pid>/cmdline` / shell history
2+
3+
**Severity:** High
4+
5+
## Location
6+
7+
- `crates/solikv-server/src/main.rs:65-67` (`--requirepass`)
8+
- `crates/solikv-server/src/main.rs:97-99` (`--cluster-password`)
9+
10+
## Issue
11+
12+
The auth password and cluster password are accepted only as `clap` arguments
13+
with `value_name = "PASSWORD"`. On Linux:
14+
15+
- `ps auxe`, `/proc/<pid>/cmdline`, and any monitoring tool that reads cmdlines
16+
expose the password to other local users.
17+
- The launching shell's history (`.bash_history`, `.zsh_history`) records it.
18+
- The daemon code (`main.rs:140-149`) re-`spawn`s itself with
19+
`std::env::args().skip(1)`, so the child process *also* has the password in
20+
its cmdline.
21+
22+
Production deployments commonly leak Redis passwords this way; SoliKV inherits
23+
the same risk and has no alternative input mechanism.
24+
25+
## Fix
26+
27+
Add support for password sources, in priority order:
28+
29+
1. `--requirepass-file <path>` / `--cluster-password-file <path>`: read a file
30+
(newline-trimmed). Recommended for production.
31+
2. `SOLIKV_PASSWORD` / `SOLIKV_CLUSTER_PASSWORD` environment variables (clap's
32+
`env = "..."` attribute).
33+
3. Keep `--requirepass <PASS>` for dev convenience but **emit a warning to
34+
stderr** when used so operators see the leak risk.
35+
36+
Refuse to start if both flag and file/env are set, to avoid silent precedence
37+
confusion.
38+
39+
When the file path is used, verify mode 0600 (warn loudly if world-readable).
40+
41+
## Verification
42+
43+
- Unit: parse args from a file successfully; warn when flag is used.
44+
- Manual: `ps -ef | grep solikv` after start with `--requirepass-file` shows
45+
no password in cmdline.
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# SEC-006 — Daemon mode uses world-writable `/tmp/solikv.pid` + `/tmp/solikv.log`, with weak process verification
2+
3+
**Severity:** High
4+
5+
## Location
6+
7+
- `crates/solikv-server/src/main.rs:106` (`pidfile = PathBuf::from("/tmp/solikv.pid")`)
8+
- `crates/solikv-server/src/main.rs:108-130` (kill-old logic)
9+
- `crates/solikv-server/src/main.rs:132-138` (`/tmp/solikv.log` opened with `create + append`)
10+
11+
## Issue
12+
13+
Three problems compound:
14+
15+
1. **Symlink attack on the log file.** `OpenOptions::new().create(true).append(true)
16+
.open("/tmp/solikv.log")` follows existing symlinks. On a multi-user host an
17+
attacker who controls `/tmp/solikv.log` (it is in a sticky-bit directory but
18+
they can win the race or pre-place a symlink before solikv first runs) can
19+
point it at any path the operator can write to (e.g. `/etc/something`,
20+
`~/.bashrc`). solikv then appends its stdout/stderr there.
21+
22+
2. **PID file race + weak verification.** Lines 113-122 read `/proc/<pid>/cmdline`
23+
and only check `.contains("solikv")`. Any cmdline containing the substring
24+
"solikv" passes — including a user's `vim /tmp/solikv-notes`, `grep solikv
25+
…`, etc. Combined with the predictable `/tmp/solikv.pid` path (which a local
26+
attacker can pre-write), this lets the attacker get solikv to send `kill` to
27+
an arbitrary PID belonging to the operator (so long as that process's
28+
cmdline mentions "solikv").
29+
30+
3. **Use of `kill(1)` subprocess** for what is a built-in syscall — extra fork,
31+
extra attack surface, and silently swallows errors with `let _ = ... .output()`.
32+
33+
## Fix
34+
35+
1. Move pidfile and log to `args.dir` (the operator-supplied data directory),
36+
defaulting to `./data`. Refuse to operate on `/tmp` paths.
37+
2. Open the log with `OpenOptions::new().custom_flags(libc::O_NOFOLLOW)` (Unix)
38+
to refuse symlinks; or open with `O_CREAT | O_EXCL` first and fall back to
39+
append-after-stat-check.
40+
3. Strengthen the PID check: parse `/proc/<pid>/exe` (a symlink to the binary)
41+
and compare to `std::env::current_exe()`. `cmdline.contains("solikv")` is
42+
not a security check.
43+
4. Replace the `Command::new("kill")` subprocess with `nix::sys::signal::kill`
44+
or `libc::kill` directly.
45+
5. After unlinking the stale pidfile, write the new one with `O_EXCL` so two
46+
concurrent daemon starts cannot both succeed.
47+
48+
## Verification
49+
50+
- Unit (where feasible): given a PID whose `/proc/<pid>/exe` does not equal our
51+
current exe, the kill path is a no-op.
52+
- Manual: `ln -s /tmp/victim /tmp/solikv.log`, run `solikv -d`, confirm solikv
53+
refuses (or creates a new file separate from the symlink target).
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# SEC-007 — Default bind is `0.0.0.0` with no password required, exposing an unauthenticated DB to the network
2+
3+
**Severity:** High
4+
5+
## Location
6+
7+
- `crates/solikv-server/src/main.rs:38-39` (`#[arg(long, default_value = "0.0.0.0")] bind`)
8+
- `crates/solikv-server/src/main.rs:65-67` (`requirepass: Option<String>` — no default)
9+
- `crates/solikv-server/src/resp_server.rs:80` (`requires_auth = password.is_some()`)
10+
11+
## Issue
12+
13+
A user who runs `solikv` with no flags gets:
14+
15+
- RESP server listening on `0.0.0.0:6379`
16+
- REST API on `0.0.0.0:5020`
17+
- No authentication required (`password = None` ⇒ `requires_auth = false`)
18+
19+
This exposes the entire database to anyone on the same network. The same
20+
default tripped Redis for years and led to a documented mass-exploitation
21+
campaign ("Redis WCRY"). The README's quickstart and Docker example both run
22+
this way.
23+
24+
The cluster-bus port at least binds to `127.0.0.1` only (`gossip.rs:336`), but
25+
the public RESP/REST surface does not.
26+
27+
## Fix
28+
29+
Pick one of these (in order of preference):
30+
31+
1. **Refuse to start unauthenticated when bind is non-loopback.** If
32+
`args.bind != "127.0.0.1"` and `args.requirepass.is_none()`, exit with
33+
a clear error pointing at `--requirepass` and `--bind 127.0.0.1`. Provide
34+
`--protected-mode no` opt-out for users who really mean it.
35+
2. Change the default `bind` to `127.0.0.1`. Document `--bind 0.0.0.0` for
36+
network exposure.
37+
38+
Approach 1 is closer to upstream Redis "protected mode" and is what most
39+
Redis-compatible projects do. Approach 2 is simpler but slightly less
40+
forgiving.
41+
42+
Also update the README quickstart and Docker examples to set `--requirepass`
43+
and/or `--bind 127.0.0.1`, and note the new behavior in
44+
`www/app/views/docs/getting_started.html.slv`.
45+
46+
## Verification
47+
48+
- Unit: `Args::parse_from(["solikv", "--bind", "0.0.0.0"])` plus the
49+
protected-mode check returns an error.
50+
- Manual: `cargo run` with no flags refuses to bind public; `cargo run --
51+
--bind 0.0.0.0 --requirepass foo` works.

0 commit comments

Comments
 (0)